.TH std::span::begin,std::span::cbegin 3 "2024.06.10" "http://cppreference.com" "C++ Standard Libary"
.SH NAME
std::span::begin,std::span::cbegin \- std::span::begin,std::span::cbegin

.SH Synopsis
   constexpr iterator begin() const noexcept;        \fB(1)\fP \fI(since C++20)\fP
   constexpr const_iterator cbegin() const noexcept; \fB(2)\fP (since C++23)

   Returns an iterator to the first element of the span.

   If the span is empty, the returned iterator will be equal to end().

   range-begin-end.svg

.SH Parameters

   \fI(none)\fP

.SH Return value

   Iterator to the first element.

.SH Complexity

   Constant.

.SH Example


// Run this code

 #include <iostream>
 #include <span>

 void print(std::span<const int> array)
 {
     std::cout << "array = ";
     for (auto it = array.begin(); it != array.end(); ++it)
         std::cout << *it << ' ';
     std::cout << '\\n';
 }

 void set_first_element(std::span<int> sp, int new_value)
 {
     if (!sp.empty())
     {
         std::cout << "old *begin = " << *sp.begin() << '\\n';
         *sp.begin() = new_value;
         std::cout << "new *begin = " << *sp.begin() << '\\n';
     }
 }

 int main()
 {
     int array[]{1, 3, 4, 5};
     print(array);
     set_first_element(array, 2);
     print(array);
 }

.SH Output:

 array = 1 3 4 5
 old *begin = 1
 new *begin = 2
 array = 2 3 4 5

.SH See also

   end     returns an iterator to the end
   cend    \fI(public member function)\fP
   (C++23)
   begin
   cbegin  returns an iterator to the beginning of a container or array
   \fI(C++11)\fP \fI(function template)\fP
   \fI(C++14)\fP
